import 'dart:async';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:heven/widget/toast.dart';

class CountdownWidget extends StatefulWidget {
  const CountdownWidget({
    super.key,
    required this.phoneNumber,
    required this.sendVerificationCode,
  });

  final String? phoneNumber; // 使用String?允许null值
  final Future<bool> Function(String) sendVerificationCode; // 发送验证码的回调函数

  @override
  State<CountdownWidget> createState() => _CountdownWidgetState();
}

class _CountdownWidgetState extends State<CountdownWidget> {
  String _text = "获取验证码";
  int _duration = 60;
  String _status = "normal";
  late Timer _timer;
  late FToast fToast;

  void initState() {
    super.initState();
    fToast = FToast();
    // if you want to use context from globally instead of content we need to pass navigatorKey.currentContext!
    fToast.init(context);
  }

  void _countdown() async {
    if (_status != 'normal') return;

    if (widget.phoneNumber == null || widget.phoneNumber!.isEmpty) {
      // 如果没有传入手机号，提示用户
      fToast.showToast(
        child: ToastWidget(text: '请输入手机号!'),
        gravity: ToastGravity.CENTER,
      );

      return;
    }

    // 手机号正则表达式，这里使用中国大陆手机号的简单校验
    final RegExp phoneRegExp = RegExp(r'^1[3-9]\d{9}$');
    if (!phoneRegExp.hasMatch(widget.phoneNumber!)) {
      // 如果手机号格式不正确，提示用户
      fToast.showToast(
        child: ToastWidget(text: '手机号格式不对!'),
        gravity: ToastGravity.CENTER,
      );
      return;
    }
    print(widget.phoneNumber);
    // 调用发送验证码的接口
    final bool isSendSuccess =
        await widget.sendVerificationCode(widget.phoneNumber!);
    print(isSendSuccess);
    if (isSendSuccess) {
      _startCountdown();
    }
  }

  void _startCountdown() {
    _status = 'countdowning';
    setState(() {
      _text = "${_duration}s";
    });
    const oneSec = Duration(seconds: 1);
    _timer = Timer.periodic(oneSec, (Timer timer) {
      if (_duration == 1) {
        _timer.cancel();
        _text = "获取验证码";
        _duration = 60;
        _status = 'normal';
        setState(() {});
      } else {
        setState(() {
          _duration--;
          _text = "${_duration}s";
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Container(
        // width: 92,
        height: 40,
        alignment: Alignment.center,
        padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
        child: Text(
          _text,
          style: const TextStyle(
            color: Colors.white,
            fontSize: 14,
            fontWeight: FontWeight.w400,
          ),
        ),
      ),
      onTap: () {
        _countdown();
      },
    );
  }
}
